package com.ruoyi.web.controller.module.wx;

import java.util.*;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.emoji.EmojiUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 微信端用户Controller
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Validated
@Api(value = "微信端用户控制器", tags = {"微信端用户管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/wx/user")
public class WxUserController extends BaseController {

    private final IWxUserService wxUserService;
	private final IEstateService estateService;
    /**
     * 查询微信端用户列表
     */
    @ApiOperation("查询微信端用户列表")
    @PreAuthorize("@ss.hasPermi('module:wxuser:list')")
    @GetMapping("/list")
    public TableDataInfo<WxUser> list(@Validated WxUser wxUser) {
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        if(StrUtil.isNotEmpty(wxUser.getPhoneNum())){
			qw.like("nick_name",wxUser.getPhoneNum()).or().like("phone_num",wxUser.getPhoneNum());
            map.put("phone_num",wxUser.getPhoneNum());
        } else if(StrUtil.isNotEmpty(wxUser.getNickName())){
			qw.like("nick_name",wxUser.getNickName()).or().like("phone_num",wxUser.getNickName());
            map.put("nick_name",wxUser.getNickName());
		}

        if(wxUser.getId()!=null){
            qw.eq("id",wxUser.getId());
            map.put("id",wxUser.getId());
        }

		if(StrUtil.isNotEmpty(wxUser.getPlatform())){
			qw.eq("platform",wxUser.getPlatform());
			map.put("platform",wxUser.getPlatform());
		}


		if(StrUtil.isNotEmpty(wxUser.getBeginDate())){
			qw.between("create_time",wxUser.getBeginDate() + " 00:00:00",wxUser.getEndDate() + " 23:59:59");
            map.put("begin_time", wxUser.getBeginDate() + " 00:00:00");
            map.put("end_time", wxUser.getEndDate() + " 23:59:59");
		}

        qw.orderByDesc("last_active_time");
        TableDataInfo<WxUser> td = PageUtils.buildDataInfo(wxUserService.selectWxUserList(PageUtils.buildPage(),map));
        List<WxUser> list = td.getRows();

        for(WxUser list1:list){
            if (list1.getLng()==null||list1.getLat()==null){
                list1.setAddress(0);
            }else if (list1.getLng()<119.66 && list1.getLng()>118.61 && list1.getLat()<36.05 && list1.getLat()>35.09 ){
                list1.setAddress(1);
            }else {
                list1.setAddress(2);
            }
        }
        list.forEach(user->{
            if(StrUtil.isNotEmpty(user.getNickName())){
                user.setNickName(EmojiUtil.toUnicode(user.getNickName()));
            }
			Estate estate = estateService.findById(user.getEstateId());
			if(estate!=null){
				user.setEstateName(estate.getEstateName());
			}
        });
        return td;
    }

    /**
     * 查询微信端用户列表
     */
    @ApiOperation("查询微信端用户列表")
    @GetMapping("/listByPhone")
    public AjaxResult listByPhone(@Validated WxUser wxUser) {
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        qw.eq("phone_num",wxUser.getPhoneNum());
        if(wxUser.getEstateId()!=null){
            qw.eq("estate_id",wxUser.getEstateId());
        }
		if (wxUser.getPlatform()!=null){
			qw.eq("platform",wxUser.getPlatform());
		}
        qw.orderByDesc("last_active_time");
        List<WxUser> list = wxUserService.list(qw);
        list.forEach(user->{
            user.setNickName(EmojiUtil.toUnicode(user.getNickName()));
        });
        return AjaxResult.success(list);
    }


    /**
     * 查询微信端用户列表
     */
    @ApiOperation("查询微信端用户列表")
    @GetMapping("/listByNickName")
    public AjaxResult listByNickName(@Validated WxUser wxUser) {
		String searchWord = wxUser.getNickName();
		if(StrUtil.isEmpty(searchWord)){
			searchWord = wxUser.getUserNo();
		}

    	if(StrUtil.isNotEmpty(searchWord)){
			QueryWrapper<WxUser> qw = new QueryWrapper<>();
			if(StrUtil.isNotEmpty(wxUser.getPlatform())){
				qw.eq("platform", wxUser.getPlatform());
			}
            if (wxUser.getNickName() != null){
				qw.and(wrapper->{
					wrapper.eq("user_no",wxUser.getNickName())
						.or().eq("phone_num",wxUser.getNickName())
						.or().like("nick_name", wxUser.getNickName());
				});
            }
			if (wxUser.getUserNo() != null){
				qw.and(wrapper->{
					wrapper.eq("user_no",wxUser.getUserNo())
						.or().eq("phone_num",wxUser.getUserNo())
						.or().like("nick_name", wxUser.getUserNo());
				});
			}
			qw.orderByDesc("last_active_time");
			List<WxUser> list = wxUserService.list(qw);
			list.forEach(user->{
				user.setNickName(EmojiUtil.toUnicode(user.getNickName()));
			});
			return AjaxResult.success(list);
		}
		List<WxUser> list = new ArrayList<>();
		return AjaxResult.success(list);
    }


    /**
     * 导出微信端用户列表
     */
    @ApiOperation("导出微信端用户列表")
    @PreAuthorize("@ss.hasPermi('module:wxuser:export')")
    @Log(title = "微信端用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<WxUser> export(@Validated WxUser wxUser) {
        Map<String, Object> map = new HashMap<>();
        if(StrUtil.isNotEmpty(wxUser.getPhoneNum())){
            map.put("phone_num",wxUser.getPhoneNum());
        } else if(StrUtil.isNotEmpty(wxUser.getNickName())){
            map.put("nick_name",wxUser.getNickName());
        }

        if(StrUtil.isNotEmpty(wxUser.getBeginDate())){
            map.put("begin_time", wxUser.getBeginDate() + " 00:00:00");
            map.put("end_time", wxUser.getEndDate() + " 23:59:59");
        }

        List<WxUser> list = wxUserService.selectWxUserList(map);
        list.forEach(user-> {
                    if (StrUtil.isNotEmpty(user.getNickName())) {
                        user.setNickName(EmojiUtil.toUnicode(user.getNickName()));
                    }
                });
        ExcelUtil<WxUser> util = new ExcelUtil<>(WxUser.class);
        return util.exportExcel(list, "微信端用户");
    }
    /**
     * 获取微信端用户详细信息
     */
    @ApiOperation("获取微信端用户详细信息")
    @PreAuthorize("@ss.hasPermi('module:wxuser:query')")
    @GetMapping("/{id}")
    public AjaxResult<WxUser> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        return AjaxResult.success(wxUserService.getById(id));
    }

    /**
     * 新增微信端用户
     */
    @ApiOperation("新增微信端用户")
    @PreAuthorize("@ss.hasPermi('module:wxuser:add')")
    @Log(title = "微信端用户", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody WxUser wxUser) {
        return toAjax(wxUserService.save(wxUser) ? 1 : 0);
    }

    /**
     * 修改微信端用户
     */
    @ApiOperation("修改微信端用户")
    @PreAuthorize("@ss.hasPermi('module:wxuser:edit')")
    @Log(title = "微信端用户", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody WxUser wxUser) {
        return toAjax(wxUserService.updateById(wxUser) ? 1 : 0);
    }

    /**
     * 删除微信端用户
     */
    @ApiOperation("删除微信端用户")
    @PreAuthorize("@ss.hasPermi('module:wxuser:remove')")
    @Log(title = "微信端用户" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(wxUserService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
    /**
     * 通过Id查询用户名
     */

    public String user_id_name(int id) {
        QueryWrapper<WxUser> qw=new QueryWrapper<>();
        qw.eq("user_no",id);
        List<WxUser> user_list=wxUserService.list(qw);
        String username=null;
        for(WxUser name:user_list){
            username=name.getNickName();
        }
        return username;
    }
    /**
     * 获取微信端用户详细信息
     */
    @ApiOperation("获取新增用户数量")
    @PreAuthorize("@ss.hasPermi('module:wxuser:query')")
    @GetMapping("/new")
    public Integer getNew(@Validated WxUser wxUser) {
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(wxUser.getBeginDate())){
            qw.between("create_time",wxUser.getBeginDate() + " 00:00:00",wxUser.getEndDate() + " 23:59:59");
        }
        TableDataInfo<WxUser> td = PageUtils.buildDataInfo(wxUserService.page(PageUtils.buildPage(),qw));
        List<WxUser> list = td.getRows();
        Integer num=list.size();
        return num;
    }
}
